package it.alertManager.activity;

import it.alertManager.exceptions.AlertManagerException;
import it.alertManager.horoscope.HTTPHoroscopeReader;
import it.alertManager.rss.HTTPRSSReader;
import it.alertManager.services.IAlertManagerService;
import it.alertManager.util.CommonData;
import it.alertManager.weather.HTTPWeatherReader;
import it.alertManager.weather.WeatherData;

import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;

public class ConfigurationActivity extends Activity implements TabHost.TabContentFactory {

	private static final String LOG_CLASS_NAME = ConfigurationActivity.class.getName();
	
	private IAlertManagerService alertManagerService = null;	
	
    private String[] zodiacSignsList = null;
    
    private TextToSpeech textToSpeech;
    private HTTPWeatherReader httpWeatherReader;
    private WeatherData weatherData;
    
    private Locale deviceLanguage;
    private ToggleButton rssAllToggleBtn;

    private boolean textToSpeechInitialized =false;
    
    private LocationManager locationManager;

	private void showNotification(Calendar calendar){
		NotificationManager  mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
        // In this sample, we'll use the same text for the ticker and the expanded notification
        CharSequence text = "Il servizio di alerting è partito....";

        // Set the icon, scrolling text and timestamp
        Notification notification = new Notification(android.R.drawable.ic_lock_idle_alarm, text,
                System.currentTimeMillis());

        // The PendingIntent to launch our activity if the user selects this notification
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, AlarmReceiveActivity.class), 0);

        // Set the info for the views that show in the notification panel.
        notification.setLatestEventInfo(this, "Notifica presente",  text, contentIntent);

        // Send the notification.
        // We use a layout id because it is a unique number.  We use it later to cancel.
        mNM.notify(R.layout.main, notification);
        alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), contentIntent);
    }
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.configuration);
		textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
			
			public void onInit(int status) {
				textToSpeechInitialized = true;
				Log.d("LOG_CLASS_NAME","STARTING SPEAKER!!!!!!!!");
			}
			
		});
		textToSpeech.setSpeechRate(CommonData.SPEACH_RATE);
		
        zodiacSignsList = getResources().getStringArray(R.array.zodiac_signs_array);
		deviceLanguage = getResources().getConfiguration().locale;
		Log.d("LOG_CLASS_NAME",deviceLanguage.getLanguage());        
//        Button configurationBtn = (Button) this.findViewById(R.id.BackMainBtn);
//        configurationBtn.setOnClickListener(new OnClickListener() {
//			
//			public void onClick(View v) {
//	            Toast.makeText(ConfigurationActivity.this, "CIAO",10).show();				
//				startActivity(new Intent(ConfigurationActivity.this, AlertManagerMainActivity.class));
//	            // Supply a custom animation.  This one will just fade the new
//	            // activity on top.  Note that we need to also supply an animation
//	            // (here just doing nothing for the same amount of time) for the
//	            // old activity to prevent it from going away too soon.
//	            overridePendingTransition(R.anim.fade, R.anim.hold);
//			}
//		});     
		TabHost tabHost = (TabHost) this.findViewById(R.id.tabhost);
		tabHost.setup();
		
		TabHost.TabSpec spec = tabHost.newTabSpec("tag1");
		spec.setContent(R.id.generalTab);
		spec.setIndicator(getResources().getText(R.string.tab_label_general), getResources().getDrawable(R.drawable.config));
		tabHost.addTab(spec);

        Button localization = (Button)findViewById(R.id.LocalBtn); 
        localization.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// Acquire a reference to the system Location Manager
				locationManager = (LocationManager) v.getContext().getSystemService(LOCATION_SERVICE);
				final Geocoder gcd = new Geocoder(v.getContext(), Locale.getDefault());
			
				// Define a listener that responds to location updates
				LocationListener locationListener = new LocationListener() {
				    public void onLocationChanged(Location location) {
				    	// Called when a new location is found by the network location provider.
				    	String city = null;
				    	List<Address> addresses = null;
						try {
							addresses = gcd.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
						} catch (IOException e) {
							e.printStackTrace();
						}
				    	if (null!= addresses && addresses.size() > 0) {
				    		 city = addresses.get(0).getLocality();
				    	}
				    	else{
				    		 List<String> providerList = locationManager.getAllProviders();
				    		 long delta = System.currentTimeMillis();
				    		 long now = System.currentTimeMillis();
				    		 Location tempLocation = null;
				    		 String bestProvider = null;
				    		 for (String provider : providerList) {
				    			 tempLocation = locationManager.getLastKnownLocation(provider);
				    			 if (null == tempLocation)
				    				 continue;
				    			 if (now - tempLocation.getTime() < delta){
				    				 delta = now - tempLocation.getTime();
				    				 bestProvider = provider;
				    			 }
							}
				    		try
				    		{
				    			tempLocation = locationManager.getLastKnownLocation(bestProvider);
								addresses = gcd.getFromLocation(tempLocation.getLatitude(), tempLocation.getLongitude(), 1);
								city = addresses.get(0).getLocality();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
				    	}
				    	new AlertDialog.Builder(ConfigurationActivity.this)
				    	.setTitle("You are in")
				    	.setIcon(R.drawable.small_blue_ball)
				    	.setMessage(city).show();
				    	locationManager.removeUpdates(this);
				    	textToSpeech.speak("Previsioni del tempo di " + city, TextToSpeech.QUEUE_ADD, null);
				    }

				    public void onStatusChanged(String provider, int status, Bundle extras) {}

				    public void onProviderEnabled(String provider) {}

				    public void onProviderDisabled(String provider) {
//				    	locationManager.getLastKnownLocation(provider)(provider)
				    }
				  };
				  Criteria criteria = new Criteria();
				  criteria.setBearingRequired(true);
				  String bestProvider = locationManager.getBestProvider(criteria, true);					  
				  locationManager.requestLocationUpdates(bestProvider,0,0,locationListener);
				
			}
		});

	       Button activateSrv = (Button)findViewById(R.id.ActivateService); 
	        activateSrv.setOnClickListener(new OnClickListener() {
	        	
	        	public void onClick(View v) {
	        		//bindService(new Intent(IAlertManagerService.class.getName()),mConnection, Context.BIND_AUTO_CREATE);
	        		Calendar dateCalendar = Calendar.getInstance();
	        		DatePickerDialog datePickerDialog = new  DatePickerDialog(v.getContext(),
	        				new OnDateSetListener() {
								
								public void onDateSet(DatePicker view, final int year, final int monthOfYear, final int dayOfMonth) {
									Calendar dateCalendar = Calendar.getInstance();
									TimePickerDialog timePickerDialog = new  TimePickerDialog(view.getContext(),
											new OnTimeSetListener() {
										
										public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
											Calendar wakeUpCalendar = Calendar.getInstance();
											wakeUpCalendar.set(Calendar.YEAR, year);
											wakeUpCalendar.set(Calendar.MONTH, monthOfYear);
											wakeUpCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
											wakeUpCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
											wakeUpCalendar.set(Calendar.MINUTE, minute);
											showNotification(wakeUpCalendar);
											
										}
									}, dateCalendar.get(Calendar.HOUR_OF_DAY), dateCalendar.get(Calendar.MINUTE), true);
									timePickerDialog.show();
									
								}
							}, dateCalendar.get(Calendar.YEAR), dateCalendar.get(Calendar.MONTH), dateCalendar.get(Calendar.DAY_OF_MONTH));
	        		datePickerDialog.show();
	        	}
	        });
		
		spec = tabHost.newTabSpec("tag2");
		spec.setContent(R.id.weatherTab);
		spec.setIndicator(getResources().getText(R.string.tab_label_weather), getResources().getDrawable(R.drawable.medium_green_ball));
        ((Button)findViewById(R.id.WeatherCityBtn)).setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
		    	String city = ((EditText) findViewById(R.id.CityText)).getText().toString();
		    	if (!"".equals(city))
		    	{
					try 
		    		{
						httpWeatherReader = new HTTPWeatherReader();
						weatherData = httpWeatherReader.getURLOfWeatherForecast(city, deviceLanguage);
						if (weatherData.getWeatherURL() == null || "".equals(weatherData.getWeatherURL()))
						{
						    new AlertDialog.Builder(ConfigurationActivity.this)
			    			.setTitle("Choose City")
			    			.setIcon(R.drawable.small_blue_ball)
			    			.setItems(weatherData.getListOfCityCS(), new DialogInterface.OnClickListener() {
								
								public void onClick(DialogInterface dialog, int which) {
									try {
										httpWeatherReader.readWeatherForecastForIt(getResources(), textToSpeech, "http://meteo.libero.it" + (weatherData.getListOfAnchorCityCS())[which], null);
									} catch (AlertManagerException e) {
										Toast.makeText(ConfigurationActivity.this, e.getMessage(), CommonData.TOAST_3_SECOND_LENGTH).show();
									}
									Log.d(ConfigurationActivity.class.getName(), "Closing dialog");	
								}
							})
							.create()
			    			.show();						
						}
						else
						{
							try {
								if (deviceLanguage.getLanguage().equals(Locale.ITALIAN.toString()))
									httpWeatherReader.readWeatherForecastForIt(getResources(), textToSpeech, weatherData.getWeatherURL(), null);
								else if (deviceLanguage.getLanguage().equals(Locale.ENGLISH.toString()))
									httpWeatherReader.readWeatherForecastForEN(getResources(), textToSpeech, weatherData.getWeatherURL(), null);
							} catch (AlertManagerException e) {
								Toast.makeText(ConfigurationActivity.this, e.getMessage(), CommonData.TOAST_3_SECOND_LENGTH).show();
							}						
							
						}
					} catch (AlertManagerException e) {
						Toast.makeText(ConfigurationActivity.this, e.getMessage(), CommonData.TOAST_3_SECOND_LENGTH).show();
					}
		    	}
			}
		}); 
		tabHost.addTab(spec);		

		spec = tabHost.newTabSpec("tag3");
		spec.setContent(R.id.rssTab);
		spec.setIndicator(getResources().getText(R.string.tab_label_rss), getResources().getDrawable(R.drawable.big_red_ball));

		// Check if the user has choosen a specif number of item
		rssAllToggleBtn = (ToggleButton) findViewById(R.id.RSSAllTBtn);
		rssAllToggleBtn.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				if (rssAllToggleBtn.isChecked())
					((EditText)findViewById(R.id.RSSNumItmEdit)).setEnabled(false);
				else
					((EditText)findViewById(R.id.RSSNumItmEdit)).setEnabled(true);
			}
		});
		
		((Button)findViewById(R.id.subscribeBtn)).setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				final ProgressDialog progressDialog = new ProgressDialog(v.getContext());
				progressDialog.setIndeterminate(true);
				progressDialog.setMessage("Messaggio");
				progressDialog.show();
				Toast.makeText(ConfigurationActivity.this, "Retrieving RSS", CommonData.TOAST_3_SECOND_LENGTH).show();
				HTTPRSSReader httprssReader = new HTTPRSSReader();
				try {
					//Default value
					int numOfItem = CommonData.ALL_RSS_ITEM;
					
					// The user can choose from only title or title and description.
					RadioButton rssTitleRadio = (RadioButton) findViewById(R.id.rssTitleRadioBtn);
					boolean onlyTitle = rssTitleRadio.isChecked();

					if (rssAllToggleBtn.isChecked() == false)
						numOfItem = Integer.parseInt(((EditText)findViewById(R.id.RSSNumItmEdit)).getText().toString());
					
					httprssReader.readRSSFromURL(getResources(), textToSpeech, ((EditText) findViewById(R.id.subscribe_url)).getText().toString(), onlyTitle, numOfItem);					
				} catch (AlertManagerException e) {
					Toast.makeText(ConfigurationActivity.this, e.getMessage(), CommonData.TOAST_3_SECOND_LENGTH).show();
				}
				
				textToSpeech.setOnUtteranceCompletedListener(new TextToSpeech.OnUtteranceCompletedListener() {
					
					public void onUtteranceCompleted(String utteranceId) {
						Log.d("LOG_CLASS_NAME","FINISHEDDDDDDDDDDDDDDDDDDD");
					}
				});		
	            new Thread() { 
                    public void run() { 
                         try{ 
                              // Do some Fake-Work 
                              sleep(5000); 
                         } catch (Exception e) {  } 
                         // Dismiss the Dialog 
                         progressDialog.dismiss(); 
                    } 
               }.start(); 
			}
		});
		tabHost.addTab(spec);

		spec = tabHost.newTabSpec("tag4");
		spec.setContent(R.id.tab4);
		spec.setIndicator(getResources().getText(R.string.tab_label_music), getResources().getDrawable(R.drawable.big_blue_ball));
		tabHost.addTab(spec);
		
		// Horoscope creation
		spec = tabHost.newTabSpec("tag5");
		spec.setContent(R.id.zodiacTab);
		spec.setIndicator(getResources().getText(R.string.tab_label_horoscope), getResources().getDrawable(R.drawable.medium_blue_ball));

		ArrayAdapter<String> zodiacSignsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, zodiacSignsList);
		zodiacSignsAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		Spinner horoscopeSpinner = ((Spinner) findViewById(R.id.horoscopeSpinner));
		horoscopeSpinner.setAdapter(zodiacSignsAdapter);	
		horoscopeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				Log.d(LOG_CLASS_NAME, getResources().getString(R.string.zodiac_selected) + " " + zodiacSignsList[arg2]);
				if (arg2 != 0)
				{
					Toast.makeText(ConfigurationActivity.this, getResources().getString(R.string.zodiac_selected) + " " + zodiacSignsList[arg2], CommonData.TOAST_3_SECOND_LENGTH).show();
					HTTPHoroscopeReader httpHoroscopeReader = new HTTPHoroscopeReader();
					String zodiacSignURL;
					try {
						zodiacSignURL = httpHoroscopeReader.getURLOfDailyHoroscope(zodiacSignsList[arg2], deviceLanguage);
						try {
							if (deviceLanguage.getLanguage().equals(Locale.ITALIAN.toString()))
								httpHoroscopeReader.readHoroscopeForIT(getResources(), textToSpeech, zodiacSignURL);	
							else if (deviceLanguage.getLanguage().equals(Locale.ENGLISH.toString()))
								httpHoroscopeReader.readHoroscopeForEN(getResources(), textToSpeech, zodiacSignURL);	
						} catch (AlertManagerException e) {
							Toast.makeText(ConfigurationActivity.this, e.getMessage(), CommonData.TOAST_3_SECOND_LENGTH).show();
						}										
					} catch (AlertManagerException e) {
						Toast.makeText(ConfigurationActivity.this, e.getMessage(), CommonData.TOAST_3_SECOND_LENGTH).show();
					}
				}

			}

			public void onNothingSelected(AdapterView<?> arg0) {
				Toast.makeText(ConfigurationActivity.this, getResources().getString(R.string.zodiac_not_selected), CommonData.TOAST_3_SECOND_LENGTH).show();
				
			}
		});
		tabHost.addTab(spec);		
		tabHost.setCurrentTab(0);  
    }

	public View createTabContent(String tag) {
		// TODO Auto-generated method stub
		return null;
	}

	 private ServiceConnection mConnection = new ServiceConnection() {
			
			public void onServiceDisconnected(ComponentName name) {
				alertManagerService = null;
				
			}
			
			public void onServiceConnected(ComponentName name, IBinder service) {
				alertManagerService = IAlertManagerService.Stub.asInterface(service);
				try {
					alertManagerService.wakeUpBoy();
				} catch (RemoteException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	            // As part of the sample, tell the user what happened.
	            Toast.makeText(ConfigurationActivity.this, "Connesso!",
	                    Toast.LENGTH_SHORT).show();			
			}
		};

	protected void onDestroy() {
		Log.d(LOG_CLASS_NAME, "Enter onDestroy");
		super.onDestroy();
		Log.d(LOG_CLASS_NAME, "textToSpeech shutting down...");
		textToSpeech.shutdown();
		Log.d(LOG_CLASS_NAME, "Exit onDestroy");
	}
}
